<template>
  <d2-container>
    <el-row>
      <el-col :lg="24">
        <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="100px">
          <el-form-item label="名称" prop="name">
            <el-input placeholder="名称" v-model="detailForm.name"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input placeholder="描述" v-model="detailForm.description"></el-input>
          </el-form-item>
          <el-form-item label="种类" prop="productCategoryName">
            <el-input
              placeholder="种类"
              v-model="detailForm.productCategoryName"
              readonly
              @focus="fnOpenPopup"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item disabled label="有效期">
                        <el-date-picker
                                v-model="detailForm.expries"
                                style="width: 100%"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
          </el-form-item>-->
          <!-- <el-form-item label="链接" prop="refLink"> -->
          <!--                        <el-input placeholder="小程序内跳转" v-model="detailForm.refLink[0].target"></el-input>-->
          <!--                        <el-input placeholder="站外跳转" v-model="detailForm.refLink[1].target"></el-input>-->
          <!-- </el-form-item> -->
          <el-form-item label="缩略图" prop="imageUrl">
            <el-upload
              class="avatar-uploader"
              :http-request="handleAvatarSuccess"
              :show-file-list="false"
            >
              <img v-if="detailForm.imageUrl" :src="detailForm.imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="轮播图" prop="swipeImage">
              <banner v-model="detailForm.swipeImage"></banner>
          </el-form-item>
          <el-form-item label="详情" prop="detail">
            <simpleRich v-model="detailForm.detail"></simpleRich>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
            <el-button @click="resetForm('detailForm')">重置</el-button>
          </el-form-item>

          <el-form-item>
            <div class="muse_control_box">
              <el-button class="muse_float_left" type="primary" @click="openAddProductSub">添加规格</el-button>
            </div>
            <el-table
              :data="productSubpagingData"
              style="width: 100%"
            >
              <el-table-column prop="attributes" label="规格" />
              <!-- <el-table-column prop="statusText" label="状态" />
              <el-table-column prop="discountPrice" label="打折价格" /> -->
              <el-table-column prop="price" label="价格" />
              <el-table-column prop="point" label="积分" />
              <el-table-column prop="stock" label="库存" />
              <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button @click="editRow(scope.row)" type="text" size="small">编辑</el-button>
                  <!-- <el-button @click="upOrDown(scope.row)" type="text" size="small">上线</el-button> -->
                  <el-button @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="muse_pagination"
              :background="true"
              @current-change="handleCurrentChange"
              :current-page="productSubpaging.page"
              :page-sizes="productSubpaging.pageSizeAry"
              :page-size="productSubpaging.pageSize"
              layout="total, prev, pager, next"
              :total="productSubpaging.total"
            ></el-pagination>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-dialog title="商品种类" :visible.sync="dialogDataVisible">
      <el-table
        :data="tableData"
        width="100%"
        ref="ref_table"
        highlight-current-row
        @current-change="handleRadioTable"
      >
        <!-- <el-table-column prop="name" label="名称"/> -->
        <el-table-column prop="name" label="名称">
          <template slot-scope="{row: {name}}">
            <span>{{name | subStr(10)}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="muse_pagination"
        :background="true"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="paging.pageSizeAry"
        :page-size="paging.pageSize"
        layout="total, prev, pager, next"
        :total="paging.total"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fnClosePopup">取 消</el-button>
        <el-button type="primary" @click="fnSaveChoosed">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加规格" :visible.sync="addProductSub">
      <el-form ref="editProductSub" :model="editProductSub" :rules="rules" label-width="100px">
        <el-form-item label="规格" prop="attributes">
          <el-input placeholder="规格" v-model="editProductSub.attributes"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input placeholder="价格" v-model="editProductSub.price"></el-input>
        </el-form-item>
        <!-- <el-form-item label="打折价格" prop="discountPrice">
          <el-input placeholder="打折价格" v-model="editProductSub.discountPrice"></el-input>
        </el-form-item>
        <el-form-item label="是否打折" prop="discountStatus">
          <el-switch
            v-model="editProductSub.discountStatus"
            active-color="#13ce66"
            active-text="打折"
            inactive-color="#ff4949"
            inactive-text="不打折"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item> -->
        <el-form-item label="积分" prop="point">
          <el-input placeholder="积分" v-model="editProductSub.point"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input placeholder="库存" v-model="editProductSub.stock"></el-input>
        </el-form-item>
        <!-- <span slot="footer" class="dialog-footer"> -->
          <el-button @click="closeProductSub">取 消</el-button>
          <el-button type="primary" @click="saveProductSub">确 定</el-button>
        <!-- </span> -->
      </el-form>
    </el-dialog>
  </d2-container>
</template>

<script>
import simpleRich from "@/components/muse/simple-rich/simple-rich";
import banner from "@/components/muse/banner/banner";
import tableMixin from "../mixins/tableMixin";
import uploadMixin from "../mixins/uploadMixin";
import {
  changeProduct,
  getOneProduct,
  getProductCategoryList,
  changeProductSub,
  getProductSubList,
  deleteProductSub
} from "@/api/admin";
export default {
  name: "productDetail",
  components: {
    simpleRich,
    banner
  },
  mixins: [uploadMixin, tableMixin],
  data() {
    return {
      id: "",
      oldDetailForm: {},
      detailForm: {
        name: "",
        description: "",
        productCategory: "",
        productCategoryName: "",
        images: [],
        imageUrl: "",
        detail: "",
        discountPrice:'',
        discountStatus:0,
        price:0,
        point:0,
        stock:0,
        refLink: ""
        // attributes:''
        //       // [
        //       // {type:'mini',target:''},
        //       //   {type:'web',target:''}
        //       // ]
      },
      editProductSub:{
        id:undefined,
        attributes:'',
        price:0,
        discountPrice:'',
        discountStatus:0,
        point:0,
        stock:0,
      },
      productSubList: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" }
        ],
        productCategoryName: [
          { required: true, message: "请选择种类", trigger: "blur" }
        ],
        detail: [{ required: true, message: "请输入详情", trigger: "blur" }],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        point: [
          { required: true, message: '请输入积分', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ],
        // images: [
        //   { required: true, message: '请输入图片', trigger: 'blur' }
        // ],
        // refLink: [
        //   { required: true, message: '请输入链接', trigger: 'blur' }
        // ]
      },
      tableData: [],
      choosedDataObj: {},
      dialogDataVisible: false,
      addProductSub: false,
      productSubpaging:{},
      productSubpagingData:[]
    };
  },
  created() {
    this.id = this.$route.query.id;
    if (this.id) {
      this.getOneProduct();
      getProductSubList({product:this.id}).then((res)=>{
        this.productSubpaging.total = res.data.total
        this.productSubpaging.pageSize = res.data.pageSize
        this.productSubpaging.page = res.data.currentPage
        this.productSubpagingData = res.data.data
        this.productSubpagingData.map(e =>{
          e.statusText = e.discountStatus == 0 ? "不打折" : "打折"
        })
      })
    }
    this.getTableData();
  },
  methods: {
    // 得到活动详情
    async getOneProduct() {
      const res = await getOneProduct({ id: this.id });
      this.detailForm = res.data;
      this.detailForm.imageUrl = this.detailForm.image;
      this.detailForm.productCategoryName = this.detailForm.productCategory[0].name;
      this.detailForm.price = this.detailForm.attribute[0].price
      this.detailForm.discountStatus = this.detailForm.discountStatus
      this.detailForm.point = this.detailForm.attribute[0].point
      this.detailForm.stock = this.detailForm.attribute[0].stock
      this.detailForm.attributes = this.detailForm.attribute[0].attributes
      // this.$nextTick(() => {
      //   this.detailForm.refLink = this.detailForm.refLink[0]
      // })
    },
    // 单图片上传
    async handleAvatarSuccess(file, type, index) {
      const url = await this.fnUpload(file);
      this.detailForm.imageUrl = url;
      this.$forceUpdate();
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.detailForm.refLink = [this.detailForm.refLink];
          if (this.id) {
            this.detailForm["id"] = this.id;
          }
          const res = await changeProduct(this.detailForm);
          this.$router.push({ name: "productdetailList" });
        } else {
          return false;
        }
      });
    },
    // 表单重置
    resetForm(formName) {
      this.$nextTick(() => {
        this.detailForm.refLink = "";
        this.detailForm.detail = "";
      });
      this.$refs[formName].resetFields();
    },

    // 打开门店弹框
    fnOpenPopup() {
      this.dialogDataVisible = true;
    },
    fnClosePopup() {
      this.dialogDataVisible = false;
      this.choosedDataObj = {};
    },
    openAddProductSub() {
      this.addProductSub = true;
    },
    closeProductSub(){
      this.addProductSub = false;
        this.editProductSub.id = undefined
        this.editProductSub.attributes = ''
        this.editProductSub.price = 0
        this.editProductSub.discountPrice = ''
        this.editProductSub.discountStatus = 0
        this.editProductSub.point = 0
        this.editProductSub.stock = 0
    },
    saveProductSub(){
      let data = this.editProductSub
      if(this.id){
        data.product = this.id
      }else{
        this.$alert('请先按“确定”保存商品', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.closeProductSub()
          }
        });
        return
      }
      changeProductSub(data).then((res)=>{
        if(res.code == 200){
          this.addProductSub = false;
      getProductSubList({product:this.id}).then((res)=>{
        this.productSubpaging.total = res.data.total
        this.productSubpaging.pageSize = res.data.pageSize
        this.productSubpaging.page = res.data.currentPage
        this.productSubpagingData = res.data.data
        this.productSubpagingData.map(e =>{
          e.statusText = e.discountStatus == 0 ? "不打折" : "打折"
        })
      })
        }
          })
    },
      deleteRow (row) {
        this.wrapConfirm(1).then(() => {
          deleteProductSub({id:row._id})
      getProductSubList({product:this.id}).then((res)=>{
        this.productSubpaging.total = res.data.total
        this.productSubpaging.pageSize = res.data.pageSize
        this.productSubpaging.page = res.data.currentPage
        this.productSubpagingData = res.data.data
        this.productSubpagingData.map(e =>{
          e.statusText = e.discountStatus == 0 ? "不打折" : "打折"
        })
      })
        }).catch(() => {})
      },
      editRow(row) {
        // console.log('edit row', row)
      this.addProductSub = true;
        this.editProductSub.id = row._id
        this.editProductSub.attributes = row.attributes
        this.editProductSub.price = row.price
        this.editProductSub.discountPrice = row.discountPrice
        this.editProductSub.discountStatus = row.discountStatus
        this.editProductSub.point = row.point
        this.editProductSub.stock = row.stock
      },
    // 获得门店列表
    async getTableData(value, type) {
      let params = {
        page:
          type === "page"
            ? value
              ? value
              : this.paging.page
            : this.paging.page,
        pageSize:
          type === "pageSize"
            ? value
              ? value
              : this.paging.pageSize
            : this.paging.pageSize
      };
      const {
        code,
        data: { total, currentPage, data, pageSize }
      } = await getProductCategoryList(params);
      this.paging.total = total;
      this.paging.pageSize = pageSize;
      this.paging.page = currentPage;
      this.tableData = data;
    },
    handleRadioTable(value) {
      this.choosedDataObj = value;
    },
    fnSaveChoosed() {
      this.detailForm.productCategory = this.choosedDataObj._id;
      this.detailForm.productCategoryName = this.choosedDataObj.name;
      this.fnClosePopup();
    }
  }
};
</script>

<style scoped>
.from_width {
  width: 40%;
}
</style>
